﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Xmef.Interfaces;
using Xmef.Library;
using Xmef.Engine;
using Isolation.Interfaces;
using Xmef.Controls;

namespace Isolation.UI
{
    public partial class Form1 : Form
    {
        private IPluginConfiguration[] _list = new IPluginConfiguration[1];
        private readonly IPluginManager _manager = new PluginManager();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LogHelper.WriteSync(">>> online");

            AutoLoadConfiguration();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AutoSaveConfiguration();

            LogHelper.WriteSync("<<< offline");
        }

        private void AutoLoadConfiguration()
        {
            _list[0] = _manager.Load<IService1>("default", "plugins.xml", true);
            PluginManagerForm.Instance.RegisterHost(_list[0].PluginHost);
        }
        private void AutoSaveConfiguration()
        {
            PluginManagerForm.Instance.UnregisterHost(_list[0].PluginHost);
            _manager.Unload<IService1>(_list[0]);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PluginManagerForm.ShowWindow(this);
        }

        bool selector;
        private void button2_Click(object sender, EventArgs e)
        {
            if (selector)
            {
                AutoLoadConfiguration();
            }
            else
            {
                AutoSaveConfiguration();
            }
            selector = !selector;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (IPluginObject obj in _list[0].ActivePlugins)
            {
                IPluginObject<IService1> o = obj as IPluginObject<IService1>;
                o.ProcessObject(service =>
                {
                    service.ShowMessage();
                });
            }
        }
    }
}
